/**
 * 包裹管理服务
 * 提供包裹的增删改查和状态管理功能
 */

import ExpressCompanyDetector from './express-company-detector.js';

class PackageService {
  static STORAGE_KEY = 'packages_list';
  static CACHE_KEY_PREFIX = 'package_cache_';

  /**
   * 生成唯一ID
   * @returns {string} UUID
   */
  static generateId() {
    return 'pkg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }

  /**
   * 获取所有包裹
   * @returns {Promise<Array>} 包裹列表
   */
  static async getAllPackages() {
    try {
      const packagesJson = uni.getStorageSync(this.STORAGE_KEY);
      if (!packagesJson) {
        return [];
      }

      const packages = JSON.parse(packagesJson);
      // 按更新时间倒序排列
      return packages.sort((a, b) => b.updateTime - a.updateTime);
    } catch (error) {
      console.error('获取包裹列表失败:', error);
      return [];
    }
  }

  /**
   * 添加包裹
   * @param {Object} packageData - 包裹数据
   * @returns {Promise<Object>} 添加的包裹
   */
  static async addPackage(packageData) {
    try {
      const {
        trackingNumber,
        expressCompany,
        expressCompanyName,
        description = '',
        status = '待揽收',
        source = 'manual' // manual, clipboard, sms
      } = packageData;

      if (!trackingNumber) {
        throw new Error('快递单号不能为空');
      }

      // 检查是否已存在
      const packages = await this.getAllPackages();
      const exists = packages.find(p => p.trackingNumber === trackingNumber);
      if (exists) {
        throw new Error('该快递单号已存在');
      }

      // 创建包裹对象
      const newPackage = {
        id: this.generateId(),
        trackingNumber,
        expressCompany: expressCompany || '',
        expressCompanyName: expressCompanyName || '未知快递',
        description,
        status,
        source,
        createTime: Date.now(),
        updateTime: Date.now(),
        isDelivered: false,
        statusHistory: [
          {
            status,
            time: Date.now(),
            description: '包裹已创建'
          }
        ]
      };

      // 保存到存储
      packages.push(newPackage);
      uni.setStorageSync(this.STORAGE_KEY, JSON.stringify(packages));

      console.log('包裹添加成功:', newPackage);
      return newPackage;
    } catch (error) {
      console.error('添加包裹失败:', error);
      throw error;
    }
  }

  /**
   * 删除包裹
   * @param {string} packageId - 包裹ID
   * @returns {Promise<void>}
   */
  static async deletePackage(packageId) {
    try {
      const packages = await this.getAllPackages();
      const filteredPackages = packages.filter(p => p.id !== packageId);

      uni.setStorageSync(this.STORAGE_KEY, JSON.stringify(filteredPackages));
      
      // 清除缓存
      uni.removeStorageSync(this.CACHE_KEY_PREFIX + packageId);

      console.log('包裹删除成功:', packageId);
    } catch (error) {
      console.error('删除包裹失败:', error);
      throw error;
    }
  }

  /**
   * 更新包裹状态
   * @param {string} packageId - 包裹ID
   * @param {string} status - 新状态
   * @param {string} description - 状态描述
   * @returns {Promise<Object>} 更新后的包裹
   */
  static async updatePackageStatus(packageId, status, description = '') {
    try {
      const packages = await this.getAllPackages();
      const packageIndex = packages.findIndex(p => p.id === packageId);

      if (packageIndex === -1) {
        throw new Error('包裹不存在');
      }

      const pkg = packages[packageIndex];
      
      // 更新状态
      pkg.status = status;
      pkg.updateTime = Date.now();
      pkg.isDelivered = status === '已签收' || status === '已送达';

      // 添加状态历史
      if (!pkg.statusHistory) {
        pkg.statusHistory = [];
      }
      pkg.statusHistory.push({
        status,
        time: Date.now(),
        description: description || status
      });

      packages[packageIndex] = pkg;
      uni.setStorageSync(this.STORAGE_KEY, JSON.stringify(packages));

      console.log('包裹状态更新成功:', pkg);
      return pkg;
    } catch (error) {
      console.error('更新包裹状态失败:', error);
      throw error;
    }
  }

  /**
   * 获取包裹详情
   * @param {string} packageId - 包裹ID
   * @returns {Promise<Object>} 包裹详情
   */
  static async getPackageDetail(packageId) {
    try {
      const packages = await this.getAllPackages();
      const pkg = packages.find(p => p.id === packageId);

      if (!pkg) {
        throw new Error('包裹不存在');
      }

      return pkg;
    } catch (error) {
      console.error('获取包裹详情失败:', error);
      throw error;
    }
  }

  /**
   * 验证快递单号格式
   * @param {string} trackingNumber - 快递单号
   * @returns {boolean} 是否有效
   */
  static validateTrackingNumber(trackingNumber) {
    if (!trackingNumber || typeof trackingNumber !== 'string') {
      return false;
    }

    const number = trackingNumber.trim();
    
    // 快递单号通常是10-20位
    if (number.length < 10 || number.length > 20) {
      return false;
    }

    // 只包含字母和数字
    return /^[A-Z0-9]+$/i.test(number);
  }

  /**
   * 自动识别快递公司
   * @param {string} trackingNumber - 快递单号
   * @returns {Object|null} 快递公司信息
   */
  static detectExpressCompany(trackingNumber) {
    return ExpressCompanyDetector.detect(trackingNumber);
  }

  /**
   * 从短信信息创建包裹
   * @param {Object} smsExpressInfo - 短信快递信息
   * @returns {Promise<Object>} 创建的包裹
   */
  static async createPackageFromSMS(smsExpressInfo) {
    try {
      const {
        trackingNumber,
        company,
        smsBody
      } = smsExpressInfo;

      // 从短信内容中提取状态
      let status = '待揽收';
      if (smsBody) {
        if (/已发货|已揽收|已收寄/.test(smsBody)) {
          status = '已发货';
        } else if (/运输中|在途|转运/.test(smsBody)) {
          status = '运输中';
        } else if (/派送中|正在派送|配送中/.test(smsBody)) {
          status = '派送中';
        } else if (/已签收|签收成功|已送达/.test(smsBody)) {
          status = '已签收';
        } else if (/待取件|到达.*自提点|到达.*驿站/.test(smsBody)) {
          status = '待取件';
        }
      }

      return await this.addPackage({
        trackingNumber,
        expressCompany: company ? company.code : '',
        expressCompanyName: company ? company.name : '未知快递',
        description: '来自短信',
        status,
        source: 'sms'
      });
    } catch (error) {
      console.error('从短信创建包裹失败:', error);
      throw error;
    }
  }

  /**
   * 更新或创建包裹（从短信）
   * @param {Object} smsExpressInfo - 短信快递信息
   * @returns {Promise<Object>} 包裹对象
   */
  static async updateOrCreateFromSMS(smsExpressInfo) {
    try {
      const { trackingNumber, smsBody } = smsExpressInfo;

      // 检查包裹是否已存在
      const packages = await this.getAllPackages();
      const existingPackage = packages.find(p => p.trackingNumber === trackingNumber);

      if (existingPackage) {
        // 更新现有包裹状态
        let status = existingPackage.status;
        let description = '';

        if (smsBody) {
          if (/已发货|已揽收|已收寄/.test(smsBody)) {
            status = '已发货';
            description = '快递已发货';
          } else if (/运输中|在途|转运/.test(smsBody)) {
            status = '运输中';
            description = '快递运输中';
          } else if (/派送中|正在派送|配送中/.test(smsBody)) {
            status = '派送中';
            description = '快递派送中';
          } else if (/已签收|签收成功|已送达/.test(smsBody)) {
            status = '已签收';
            description = '快递已签收';
          } else if (/待取件|到达.*自提点|到达.*驿站/.test(smsBody)) {
            status = '待取件';
            description = '快递待取件';
          }
        }

        return await this.updatePackageStatus(existingPackage.id, status, description);
      } else {
        // 创建新包裹
        return await this.createPackageFromSMS(smsExpressInfo);
      }
    } catch (error) {
      console.error('更新或创建包裹失败:', error);
      throw error;
    }
  }

  /**
   * 获取活跃包裹数量（未签收）
   * @returns {Promise<number>} 活跃包裹数量
   */
  static async getActivePackageCount() {
    try {
      const packages = await this.getAllPackages();
      return packages.filter(p => !p.isDelivered).length;
    } catch (error) {
      console.error('获取活跃包裹数量失败:', error);
      return 0;
    }
  }

  /**
   * 清除所有包裹
   * @returns {Promise<void>}
   */
  static async clearAllPackages() {
    try {
      uni.removeStorageSync(this.STORAGE_KEY);
      console.log('所有包裹已清除');
    } catch (error) {
      console.error('清除包裹失败:', error);
      throw error;
    }
  }

  /**
   * 导出包裹数据
   * @returns {Promise<string>} JSON字符串
   */
  static async exportPackages() {
    try {
      const packages = await this.getAllPackages();
      return JSON.stringify(packages, null, 2);
    } catch (error) {
      console.error('导出包裹数据失败:', error);
      throw error;
    }
  }

  /**
   * 导入包裹数据
   * @param {string} jsonData - JSON字符串
   * @returns {Promise<void>}
   */
  static async importPackages(jsonData) {
    try {
      const packages = JSON.parse(jsonData);
      if (!Array.isArray(packages)) {
        throw new Error('数据格式错误');
      }

      uni.setStorageSync(this.STORAGE_KEY, JSON.stringify(packages));
      console.log('包裹数据导入成功');
    } catch (error) {
      console.error('导入包裹数据失败:', error);
      throw error;
    }
  }
}

export default PackageService;
